# -*-coding:Utf-8 -* 
""" Link module
Part of common module
"""

class Link(object):
	
	@classmethod
	def get(cls,obj,name):
		if name in obj.__dict__ and isinstance(obj.__dict__[name], Link):
			return obj.__dict__[name]
		return 0
		
	@classmethod
	def offsetlink(cls, obj, offset, link, name = None):
		if name != None and name in link.__dict__ and isinstance(link.__dict__[name], Link):
			link = link.__dict__[name]
		if isinstance(link, Link) and link._base_ob and callable(offset):
			obj.__class__.__setattr__(obj,'_link_offset_'+str(link._name),offset)
	
	def __init__(self, obj, propName,value = None):
		self._base_ob = obj
		self._name = str(propName)
		obj.__class__.__setattr__(obj, '_link_value_'+str(propName), value)
		if value == None and propName and hasattr(obj,propName):
			self._base_ob.__class__.__setattr__(self._base_ob, '_link_value_'+str(propName), getattr(obj,propName))
		obj.__class__.__setattr__(obj,propName,self)
	
	@property
	def name(self):
		return self._name
		
	def __get__(self, instance, owner):
		if instance == None:
			return self
		if self._base_ob:
			if hasattr(instance, '_link_offset_'+self._name):
				return getattr(instance, '_link_offset_'+self._name)(self._base_ob.__dict__['_link_value_'+self._name])
			return getattr(self._base_ob, '_link_value_'+self._name)
		return self._name
		
	def __set__(self, instance, value):
		if isinstance(value, Link):
			self._base_ob.__class__.__setattr__(self._base_ob, self._name, value)
		else:
			self._base_ob.__class__.__setattr__(self._base_ob,'_link_value_'+self._name, value)
		
	def __delete__(self, instance):
		if '_link_value_'+self._name in self._base_ob.__dict__:
			self._name = getattr(self._base_ob, '_link_value_'+self._name)
			self._base_ob.__class__.__delattr__(self._base_ob, '_link_value_'+self._name)
		self._base_ob = None
	
